package com.eden.manage.service;

import com.eden.manage.dto.PageComDto;
import com.eden.manage.dto.UserInfoDto;
import com.eden.manage.dto.agent.AgentProfitDto;
import com.eden.manage.mapper.EdenAgentProfitParamMapper;
import com.eden.manage.model.EdenAgentProfitParam;
import com.eden.manage.req.query.AgentProfitQuery;
import com.eden.manage.utils.WebUserUtils;
import com.eden.manage.utils.mapstruct.PlatStructUtils;
import eden.api.common.enums.UserTypeEnum;
import eden.api.common.model.PageQuery;
import eden.api.common.utils.ErrorEnums;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@RequiredArgsConstructor
public class AgentProfitService {

    private final EdenAgentProfitParamMapper platProfitParamMapper;

    public PageComDto<AgentProfitDto> pageList(AgentProfitQuery profitQuery){
        dealAuth(profitQuery);
        PageComDto<AgentProfitDto> pageDto = new PageComDto<>();
        int count = platProfitParamMapper.countByPage(profitQuery);
        if(count > 0){
            List<AgentProfitDto> profitDtos = platProfitParamMapper.selectPageList(profitQuery);
            pageDto.setList(profitDtos);
        }
        pageDto.setCount(count);
        return pageDto;
    }

    private void dealAuth(PageQuery profitQuery) {
        UserInfoDto userInfo = WebUserUtils.getUserInfo();
        if(userInfo.getType().equals(UserTypeEnum.PLAT.getCode())){
            String sb = "plat_id=" +
                    userInfo.getPlatId();
            profitQuery.setDataAuth(sb);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void savePlatParam(AgentProfitDto agentProfitDto){
        UserInfoDto userInfo = WebUserUtils.getUserInfo();
        if(userInfo.getType().equals(UserTypeEnum.ADMIN.getCode())){
            throw new IllegalArgumentException(ErrorEnums.ADMIN_NOT_OPT.name());
        }
        EdenAgentProfitParam profitParam = PlatStructUtils.INSTANCE.convertParamDtoToDB(agentProfitDto);
        if(agentProfitDto.getId() == null || agentProfitDto.getId() <= 0){
            profitParam.setPlatId(userInfo.getPlatId());
            platProfitParamMapper.insert(profitParam);
        }else{
            platProfitParamMapper.updateParam(agentProfitDto);
        }

    }

}
